<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/4/19 0019
 * Time: 下午 5:11
 */
class Base_Controller extends  CI_Controller
{
    public function __construct(){
        parent::__construct();
    }

    function success($data=array(),$msg="成功"){
        $result['code'] = 1;
        $result['msg'] = $msg;
        $result['data'] = $data;
        if (isset($_GET['callback']) || isset($_POST['callback'])) {
            if(isset($_GET['callback']))
            {
                $callbace = $_GET['callback'];
            }else{
                $callbace = $_POST['callback'];

            }
            $data = $this->filterJsonData($result);
            exit($callbace . '(' .json_encode($data) . ')');
        }else{
            $this->echoJsonData($result);
        }
        exit;
    }


    protected function error($msg = 'error',$data='') {
        $result ['code'] = '-1';
        $result ['msg'] = (string)$msg;
        $result ['data'] = empty($data)?(object)array():$data;
        if (isset($_GET['callback']) || isset($_POST['callback'])) {
            if(isset($_GET['callback']))
            {
                $callbace = $_GET['callback'];
            }else{
                $callbace = $_POST['callback'];

            }
            $data = $this->filterJsonData($result);
            exit($callbace . '(' .json_encode($data) . ')');
        }else{
            $this->echoJsonData($result);
        }
        exit ();
    }

    /**
     * 输出json数据
     * @param  array $data
     * @return void
     */
    protected function echoJsonData($data){
        $data = $this->filterJsonData($data);
        echo json_encode($data);
    }

    /**
     * 过滤输出json数据
     * @param  array|string|int $data
     * @return string|int
     */
    protected function filterJsonData($data){
        if($data === null){
            return '';
        }
        elseif (empty($data)) {
            return $data;
        } else {
            return is_array($data) ? array_map(array(&$this, 'filterJsonData'), $data) : ($data === null ? '' : $data);
        }
    }
}